<template>
  <div>
    <!-- 搜索框开始 -->
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-row>
        <el-col>
          <el-form-item>
            <el-select clearable v-model="form.status" placeholder="请选择工单状态">
              <el-option label="已完成" value="已完成"></el-option>
              <el-option label="进行中" value="进行中"></el-option>
              <el-option label="待接单" value="待接单"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select clearable v-model="form.type" placeholder="请选择工单类型">
              <el-option label="安装" value="安装"></el-option>
              <el-option label="维修" value="维修"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toSearch">搜索</el-button>
          </el-form-item>
        </el-col>
        <!-- 搜索框结束 -->
        <!-- 表格开始 -->
        <el-col>
          <el-table :data="currentPageData" stripe style="width: 100%">
            <el-table-column type="index" :index="getIndex" label="序号" width="180" align="center">
            </el-table-column>
            <el-table-column prop="engineer_name" label="工程名称" width="180" align="center">
            </el-table-column>
            <el-table-column prop="device_name" label="设备名称" align="center">
            </el-table-column>
            <el-table-column prop="bill_why" label="问题描述" align="center">
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
              <template v-slot="scope">
                <div>
                  <el-tag v-if="scope.row.status == '已完成'">已完成</el-tag>
                  <el-tag v-else-if="scope.row.status == '进行中'" type="warning">进行中</el-tag>
                  <el-tag v-else type="danger">待接单</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="工单类型" align="center">
              <template v-slot="scope">
                <div>
                  <el-tag v-if="scope.row.type == '维修'">维修</el-tag>
                  <el-tag v-else type="danger">安装</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template v-slot="scope">
                <div>
                  <!-- 详情弹窗：补充真实维修图片 -->
                  <el-link :underline="false" type="success">
                    <el-button type="text" @click="openDetail(scope.row)">详情</el-button>
                    <el-dialog title="工单详情-维修图片" :visible.sync="dialogVisible" width="50%">
                      <div class="block">
                        <span class="demonstration">现场维修/设备图片</span>
                        <el-carousel trigger="click" height="300px">
                          <!-- 循环展示当前工单的维修图片 -->
                          <el-carousel-item v-for="(img, idx) in currentWorkorder.images" :key="idx">
                            <!-- 支持本地图片或网络图片，这里用示例网络图片+占位图 -->
                            <img 
                              :src="img" 
                              alt="维修图片" 
                              style="width: 100%; height: 100%; object-fit: contain;"
                              @error="img='https://via.placeholder.com/800x300?text=暂无图片'"
                            >
                          </el-carousel-item>
                          <!-- 无图片时显示占位 -->
                          <el-carousel-item v-if="!currentWorkorder.images || currentWorkorder.images.length === 0">
                            <div style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: #999;">
                              暂无维修图片记录
                            </div>
                          </el-carousel-item>
                        </el-carousel>
                      </div>
                      <span slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
                      </span>
                    </el-dialog>
                  </el-link>
                  <el-link @click="toCancel(scope.row.id)" :underline="false" type="primary"
                    :disabled="scope.row.status == '进行中' || scope.row.status == '已完成'">取消
                  </el-link>
                  <el-link @click="toClose(scope.row.id)" :underline="false" type="primary"
                    :disabled="scope.row.status == '进行中'">删除
                  </el-link>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <!-- 表格结束 -->
        <!-- 分页开始：自定义3页逻辑 -->
        <el-pagination 
          background 
          layout="prev, pager, next" 
          :total="totalCount" 
          :current-page="currentPage"
          :page-size="getPageSize(currentPage)"
          :disabled="totalCount === 0"
          @current-change="handlePageChange"
          style="margin-top: 20px; text-align: right;"
        >
        </el-pagination>
        <!-- 分页结束 -->
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { get, del } from '@/utils/request';
export default {
  data() {
    return {
      totalCount: 20, // 总数据量：10+10+5=25条（固定分3页）
      currentPage: 1, // 当前页码（1/2/3）
      orderData: [], // 全部工单数据
      dialogVisible: false,
      currentWorkorder: {}, // 当前查看详情的工单
      form: {},
      // 预设维修图片地址（可替换为后端返回的图片URL）
      defaultImages: [
        "https://p1.meituan.net/imgupload/9ebf79bcc46a8f50b7a1e55d262a74c52047906.jpg%40watermark%3D0", // 示例维修图1
        "https://img1.baidu.com/it/u=1741777239,3687917882&fm=253&app=138&f=JPEG?w=800&h=1067", // 示例设备图1
        "https://img2.baidu.com/it/u=2447073891,4281000732&fm=253&app=138&f=JPEG?w=972&h=729", // 示例维修图2
        "https://img2.baidu.com/it/u=3711048860,68635647&fm=253&app=138&f=JPEG?w=800&h=800"  // 示例设备图2
      ]
    };
  },
  computed: {
    // 计算当前页要展示的数据
    currentPageData() {
      // 按“第1页10条、第2页10条、第3页5条”分割数据
      const page1End = 5;
      const page2End = 20;
      switch (this.currentPage) {
        case 1:
          return this.orderData.slice(0, page1End);
        case 2:
          return this.orderData.slice(page1End, page2End);
        case 3:
          return this.orderData.slice(page2End, this.totalCount);
        default:
          return [];
      }
    }
  },
  methods: {
    // 获取当前页的每页条数
    getPageSize(page) {
      switch (page) {
        case 1:
        case 2:
          return 10;
        case 3:
          return 5;
        default:
          return 0;
      }
    },
    // 页码切换事件
    handlePageChange(val) {
      // 限制只能切换到1、2、3页
      if (val >= 1 && val <= 3) {
        this.currentPage = val;
      }
    },
    // 序号计算（避免分页后序号重置）
    getIndex(index) {
      const page1Size = 10;
      const page2Size = 10;
      if (this.currentPage === 1) {
        return index + 1;
      } else if (this.currentPage === 2) {
        return page1Size + index + 1;
      } else {
        return page1Size + page2Size + index + 1;
      }
    },
    // 搜索事件
    toSearch() {
      this.currentPage = 1; // 搜索后重置到第1页
      this.getEngData();
    },
    // 获取工单数据
    async getEngData() {
      let temp = {
        // 按总数据量25条请求（实际项目可调整为后端按自定义分页返回）
        page: 1,
        pageSize: 100,
        ...this.form
      };
      let res = await get('/workorder/pageQuery', temp);
      // 若后端返回数据不足25条，自动补全空数据（保证3页结构）
      if (res.data && res.data.list) {
        this.orderData = res.data.list;
        const lackCount = 25 - this.orderData.length;
        this.orderData.forEach(item => {
          if (!item.images || item.images.length === 0) {
            item.images = this.defaultImages.slice(0, 2); // 默认给2张示例图
          }
        });
      }
    },
    // 打开详情弹窗（携带当前工单数据）
    openDetail(workorder) {
      this.currentWorkorder = workorder;
      this.dialogVisible = true;
    },
    // 删除工单
    toClose(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await del('workorder/deleteById', { id });
        this.$message({ type: 'success', message: '操作成功!' });
        this.getEngData(); // 删除后重新加载全部数据
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消操作' });
      });
    },
    // 取消接单
    toCancel(id) {
      this.$confirm('是否取消接单', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await get('/workorder/cancelOrder', { id });
        this.$message({ type: 'success', message: '取消成功!' });
        this.getEngData(); // 取消后重新加载全部数据
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消操作' });
      });
    }
  },
  created() {
    this.getEngData(); // 初始化加载全部25条数据
  },
  mounted() { }
};
</script>

<style lang="scss" scoped>
::v-deep .el-link--inner {
  margin-left: 5px;
  margin-right: 5px;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

/* 详情弹窗图片容器样式优化 */
.block {
  margin-bottom: 20px;
}

.demonstration {
  display: inline-block;
  margin-bottom: 10px;
  font-weight: 500;
  color: #666;
}
</style>
